package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeRepository;

import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.sql.Timestamp;
import java.util.Date;
import java.util.Random;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {
    @Autowired
    private AuthCodeRepository authCodeRepository;

    @Override
    @Transactional
    public String generateCode(String email) {
        Random r = new Random();
        int randomNumber = r.nextInt(10000);
        String code = String.format("%04d", randomNumber);

        AuthCode authCode = authCodeRepository.findByEmail(email);
        if (authCode == null) {
            AuthCode authCodeToCreate = new AuthCode();

            authCodeToCreate.setEmail(email);
            authCodeToCreate.setCode(code);
            authCodeToCreate.setCreatetime(new Timestamp((new Date()).getTime()));
            authCodeToCreate.setExpiretime(new Timestamp((new Date()).getTime()));

            authCodeRepository.save(authCodeToCreate);

            return authCodeToCreate.getCode();
        }
        else {
            authCode.setCode(code);

            authCode.setCreatetime(new Timestamp((new Date()).getTime()));
            authCode.setExpiretime(new Timestamp((new Date()).getTime()));

            authCodeRepository.save(authCode);

            return authCode.getCode();
        }
    }

    @Override
    public String validate(String email, String code) {
        AuthCode authCode = authCodeRepository.findByEmail(email);
        if (authCode == null) {
            return "1";
        }

        if (!code.equals(authCode.getCode())) {
            return "1";
        }

        long timeNow = new Date().getTime();
        long timeDiff = timeNow - authCode.getExpiretime().getTime();
        if (timeDiff > 1000L * 60 * 5) {
            return "2";
        }

        return "0";
    }

}
